package com.label.Web;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.ImmutableMap;
import com.label.Config.Logger.LogAnnotation;
import com.label.Dao.PersonsAppMapper;
import com.label.Model.Common.ResponseBean;
import com.label.Model.Do.Persons;
import com.label.Model.Do.PersonsApp;
import com.label.Model.Do.User;
import com.label.Model.Query.UserQuery;
import com.label.Service.PersonsAppService;
import com.label.Service.PersonsService;
import com.label.Service.UserService;
import com.label.Utils.ExcelUtils;
import com.label.Utils.FileUtils;
import com.label.Utils.MailUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Example;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class PersonsAppController {

    @Resource
    private PersonsAppService personsAppService;

    @Resource
    private PersonsService personsService;

    @Resource
    private UserService userService;

    @Resource
    @Qualifier("oracleJdbcTemplate")
    private JdbcTemplate oracleJdbc;

    @Resource
    @Qualifier("sparkSqlJdbcTemplate")
    private JdbcTemplate sparkJdbc;

    @RequestMapping("/appAdd")
    @LogAnnotation(module = "应用模块",operator = "增加应用")
    @RequiresAuthentication
    public ResponseBean appAdd(@RequestBody PersonsApp personsApp){
        PersonsApp personsA=personsAppService.addApp(personsApp);
        if(personsA!=null)
            return new ResponseBean(HttpStatus.OK.value(), "增加成功(Query was successful)",personsA);
        return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "保存失败",null);
    }

    @RequestMapping("/appDelete")
    @LogAnnotation(module = "应用模块",operator = "应用删除")
    @RequiresAuthentication
    public ResponseBean appDelete(@RequestBody PersonsApp personsApp){
        if(personsApp.getId()==null)
            return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "参数错误",null);
        if(personsAppService.delAppById(personsApp))
            return new ResponseBean(HttpStatus.OK.value(), "删除成功(Query was successful)",null);
        return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "此应用不存在",null);
    }

    @RequestMapping("/appGet")
    @LogAnnotation(module = "应用模块",operator = "获取所有应用")
    @RequiresAuthentication
    public ResponseBean appGet(@RequestBody PersonsApp personsApp){
        return new ResponseBean(HttpStatus.OK.value(), "查找成功(Query was successful)",personsAppService.getApp(personsApp));
    }

    @RequestMapping("/appGetOne")
    @LogAnnotation(module = "应用模块",operator = "根据ID获取一项应用")
    @RequiresAuthentication
    public ResponseBean appGetOne(@RequestBody PersonsApp personsApp){
        if(personsApp.getId()==null)
            return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "参数错误",null);
        return new ResponseBean(HttpStatus.OK.value(), "查找成功(Query was successful)",personsAppService.getOneById(personsApp));
    }

    @RequestMapping("/appUpdate")
    @LogAnnotation(module = "应用模块",operator = "应用更新")
    @RequiresAuthentication
    public ResponseBean appUpdate(@RequestBody PersonsApp personsApp){
        PersonsApp personsA=personsAppService.updateApp(personsApp);
        if(personsA!=null)
            return new ResponseBean(HttpStatus.OK.value(), "更新成功(Query was successful)",personsA);
        return new ResponseBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), "此应用不存在",null);
    }

    @RequestMapping("/appGetAll")
    @LogAnnotation(module = "应用模块",operator = "获取所有应用")
    @RequiresAuthentication
    public ResponseBean appGetAll(){
        return new ResponseBean(HttpStatus.OK.value(), "查找成功(Query was successful)",personsAppService.getAllApp());
    }

    @RequestMapping("/sendMail")
    @LogAnnotation(module = "应用模块",operator = "向指定人员发送Email")
    @RequiresAuthentication
    public ResponseBean sendMail(@RequestParam String appid) throws IOException {
        Map<String,Object> res=oracleJdbc.queryForMap("select app_unitid,app_roleid,app_userid from personas_app where app_id='"+appid+"'");
        List<String> emils=new ArrayList<>();
        if(res.get("APP_USERID")!=null){
            User userDO=userService.getById(Long.parseLong(res.get("APP_USERID").toString()));
            if(userDO.getEmail()!=null)
                emils.add(userDO.getEmail());
        }else {
            if(res.get("APP_ROLEID")!=null){
                UserQuery userQuery=new UserQuery();
                userQuery.setRoles(Collections.singletonList(Long.parseLong(res.get("APP_ROLEID").toString())));
                List<User> users=userService.getAllUserByRoles(userQuery);
                emils.addAll(users.stream().map(User::getEmail).filter(Objects::nonNull).collect(Collectors.toList()));
            }
            else {
                if(res.get("APP_UNITID")!=null){
                    List<User> users=userService.list(new QueryWrapper<User>().lambda().eq(User::getUnitId,res.get("APP_UNITID").toString()));
                    emils.addAll(users.stream().map(User::getEmail).filter(Objects::nonNull).collect(Collectors.toList()));
                }
            }
        }
        String[] s = emils.toArray(new String[emils.size()]);
        
        
        Map<String,Object> app=oracleJdbc.queryForMap("select * from personas_app where app_id="+appid);
        String filename=app.get("APP_NAME").toString();
        List<Map<String,String>> info = (List<Map<String,String>>)JSONArray.parse(app.get("PERSONAS_INFO").toString());
        List<List<Map<String,Object>>> resdata=new ArrayList<>();
        String[] titles=new String[info.size()];
        List<Persons> persons=new ArrayList<>();
        Map<String,String> classMap=oracleJdbc.queryForList("select id,class_name from class").stream().collect(Collectors.toMap(p->p.get("ID").toString(),p->p.get("CLASS_NAME").toString()));
        Map<String,String> majorMap=oracleJdbc.queryForList("select major_id,major_name from major").stream().collect(Collectors.toMap(p->p.get("MAJOR_ID").toString(),p->p.get("MAJOR_NAME").toString()));
        Map<String,String> sexMap=ImmutableMap.of("1","男","2","女");

        int count=0;
        for(Map<String,String> m:info){
//            String selectsql="select userid,username,sex,enrollyear,classid,majorid,politics,classposition,dormitory from (select entityid from personportraitdatapar where portraitid='"+String.valueOf(m.get("usergroup"))+"' and theme='studentprofile') b inner join  studentattr a on a.userid=b.entityid";
//            List<Map<String,Object>> temp=sparkJdbc.queryForList(selectsql);
            String selectsql="select userid,username,sex,enrollyear,classid,majorid,politics,classposition,dormitory from (select entityid from personportraitdatapar where portraitid='"+String.valueOf(m.get("usergroup"))+"' and theme='studentprofile') b inner join  studentattr a on a.userid=b.entityid";
            List<Map<String,Object>> temp=oracleJdbc.queryForList(selectsql);
            for(Map<String,Object> use:temp){
                use.put("sex",sexMap.get(use.get("sex")));
                use.put("classid",classMap.get(use.get("classid")));
                use.put("majorid",majorMap.get(use.get("majorid")));
            }
            resdata.add(temp);
            persons.add(personsService.getById(Long.valueOf(String.valueOf(m.get("usergroup")))));
            titles[count++]=String.valueOf(m.get("name"));
        }

        String path= ExcelUtils.getInstance().createNewExcel(resdata,filename,titles,persons);
        File file=new File(path);
        if(s.length>0)
            MailUtil.sendMessage(file,s,filename);
        else {
            FileUtils.deleteFile(path);
            return new ResponseBean(200,"无可用邮箱",null);
        }
        FileUtils.deleteFile(path);
        return new ResponseBean(200,"推送成功",null);
    }

}
